<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;

class PostsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->except(['index', 'show']);
    }

    public function index()
    {
        $posts = Post::latest()
            ->filter(\request(['year', 'month']))
            ->get();
        return view('posts.index', compact('posts'));
    }

    public function create()
    {
        return view('posts.create');
    }


    public function store(Request $request)
    {
        $this->validate(\request(), [
            'title' => 'required|unique:posts|max:25',
            'body' => 'required|min:5',
        ]);

        /*
        way 1:

        $post = new Post();
        $post->title = \request('title');
        $post->body = \request('body');
        $post->save();
        */


        /*
        way 2
        Post::create([
            'title'=>request('title'),
            'body'=>request('body'),
        ]);
        */

        //way 3
        //Post::create(\request(['title','body']));
        $post = new Post(\request(['title', 'body']));

        auth()->user()->publishPost($post);

        return redirect('posts');
    }

    public function show(Post $post)
    {
        return view('posts.show', compact('post'));
    }
}
